package com.zm.tools.util.core;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Enumeration;

/**
 * @author zoum
 * @date 2018/6/6 18:34.
 */
public class HttpUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);


    public static <T>T doThirdRequest(String url, Object param, String requestMethod, String contentType ,Class<T> resultClazz) {
        HttpURLConnection http = null;
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        String paramString = JSONObject.toJSONString(param);
        try {
            URL tourl = new URL(url);
            http = (HttpURLConnection) tourl.openConnection();
            http.setDoOutput(true);
            http.setDoInput(true);
            http.setRequestMethod(requestMethod);
            if (contentType == null || contentType.trim().length() == 0){
                http.setRequestProperty("Content-type","application/json");
            }else {
                http.setRequestProperty("Content-type", contentType);
            }
            http.connect();

            if(param != null && param.toString().trim().length() > 0){
                out = new OutputStreamWriter(http.getOutputStream(), "UTF-8");
                String json = JSONObject.toJSONString(param);
                out.append(json);
                out.flush();
            }

            if (http.getResponseCode() != HttpURLConnection.HTTP_OK){
                LOGGER.error("P3|ERROR|ERROR|ERROR|request error, url is {}, responseCode is {}, error message is {}"
                        , new Object[]{url, http.getResponseCode(), http.getResponseMessage()});
                return null;
            }

            reader = new BufferedReader(new InputStreamReader(http.getInputStream(), "UTF-8"));

            String line;
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            LOGGER.info("E|normal|http redict|{}|request end, url is {}, result is {}", new Object[]{url, url, buffer});
            return JSONObject.parseObject(buffer.toString(), resultClazz);
        } catch (Exception e){
            LOGGER.error("P3|ERROR|ERROR|{}|request error, url is {}, error message is ", new Object[]{e.getMessage(), url, e});
            return null;
        } finally {
            try {
                if (http != null){
                    http.disconnect();
                }
                if (out != null){
                    out.close();
                }
                if (reader != null){
                    reader.close();
                }
            }catch (IOException e){
                LOGGER.error("P3|{}| request end, url is {}, error message is ", new Object[]{e.getMessage(), url, e});
            }
        }
    }

    public static <T>T doThirdRequest(String url, Object param, String requestMethod, Class<T> resultClazz) {
        return doThirdRequest(url, param, requestMethod, null, resultClazz);
    }

    public static <T>T doRequest(String baseUrl, HttpServletRequest request, Class<T> clazz){
        try {
            String url = baseUrl + getUrlFromRequest(request);
            Object param = JSONObject.parseObject(request.getInputStream(), Charset.forName("UTF-8"),Object.class,null);
            return doThirdRequest(url, param, request.getMethod(), clazz);
        } catch (Exception e){
            LOGGER.error("P3|ERROR|ERROR|{}|", e.getMessage(), e);
            return JSONObject.parseObject("网络异常，请稍后再试.", clazz);
        }
    }

    private static String getUrlFromRequest(HttpServletRequest request) throws Exception{
        String url = request.getRequestURI();
        String queryString = request.getQueryString();
        if (queryString != null && queryString.trim().length() > 0){
            url = url + "?" + queryString;
        }
        return url;
    }

    public static String getUrlFromRequestPost(HttpServletRequest request){
        try {
            StringBuilder url = new StringBuilder();
            url.append(request.getRequestURI());
            Enumeration<String > parameterNames= request.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String paramName = parameterNames.nextElement();
                if (url.indexOf("?") == -1){
                    url.append("?").append(paramName).append("=").append(URLEncoder.encode(request.getParameter(paramName), "UTF-8"));
                }else {
                    url.append("&").append(paramName).append("=").append(URLEncoder.encode(request.getParameter(paramName), "UTF-8"));
                }
            }
            return url.toString();
        } catch (Exception e){
            LOGGER.error("P3|ERROR|ERROR|{}|", e.getMessage(),  e);
            return null;
        }
    }

}
